/*
 * Copyright 2011-2012 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sabayframework.activity.impl;

import org.sabayframework.activity.ActivityContext;
import org.sabayframework.channel.Channel;
import org.sabayframework.channel.Lock;

/**
 * Base class for activities that do not require any input.
 * @author Alex Antonau
 * */
public abstract class OutputActivity<O> extends StatefulActivity<O, O> {
	
	private boolean closeOutput;
	
	public OutputActivity() {
		this(true);
	}
	/**
	 * @param closeOutput if true then activity closes output channel after execution. Default is true.
	 */
	public OutputActivity(boolean closeOutput) {
		super();
		super.setState(null, State.PROCESS);
		this.closeOutput = closeOutput;
	}

	protected void setCloseOutput(boolean closeOutput) {
		this.closeOutput = closeOutput;
	}
	
	@Override
	public void setState(ActivityContext<O, O> ctx, State state) {
		//never set READY state to avoid input
		if(state == State.READY) state = State.PROCESS;
		super.setState(ctx, state);
	}

	@Override
	public boolean isDone(ActivityContext<O, O> ctx) throws Exception {
		final Channel<O> output = ctx.getOutput();
		if(output.isClosed()) {
			final Channel<O> input = ctx.getInput();
			if(input != null){
				if(output.hasFailed()) input.fail(output.getFailureCause());
				else {
					input.close();
				}
			}
			return true;
		}
		return false;
	}

	@Override
	public final void input(ActivityContext<O, O> ctx, Lock<O> inputLock)	{}

	@Override
	public void afterExecute(ActivityContext<O, O> ctx) throws Exception {
		if(closeOutput)super.afterExecute(ctx);
	}

}
